const axios = require('axios');
const qs = require('querystring');

module.exports = class extends enkel.controller.base {
  init (http) {
    super.init(http);

    this.UserScriptModel = this.models('enkel/userscript');

    this.Op = this.Sequelize.Op;

    this.response.setHeader('Access-Control-Allow-Origin', '*');
    this.response.setHeader('Access-Control-Allow-Headers', '*');
    this.response.setHeader('Access-Control-Allow-Methods', '*');
  }

  // async addAction () {
  //   // await this.UserScriptModel.create({
  //   //   name: 'BG',
  //   //   desc: '修改页面背景色',
  //   //   author: 'Keith',
  //   //   url: 'https://static.dei2.com/scripts/us.js',
  //   //   match: '*'
  //   // });
  //   await this.UserScriptModel.create({
  //     name: 'BG22',
  //     desc: '修改页面背景色2222',
  //     author: 'Keith',
  //     url: 'https://static.dei2.com/scripts/us.js',
  //     match: 'baidu.com/*'
  //   });
  //   return this.json({ status: 200, message: '添加成功' });
  // }

  async queryAction () {
    if (!this.isPost()) {
      return this.json({ status: 405, message: '请求方法不正确', data: {} });
    }
    let params = await this.post();
    // let params = this.get();
    // params.host = 'www.baidu.com/sf/'
    if (params.host === '') {
      return this.json({
        status: 200,
        data: {
          scripts: [],
        },
        message: '成功'
      })
    }
    let _script = await this.UserScriptModel.findAll({
      attributes: { exclude: ['createdAt', 'updatedAt', 'id'] }
    })
    _script = _script.filter(item => {
      let str = item.match.replace(/(\^|\.|\?|\!|\/|\\|\$|\#|\&|\||,|\[|\]|\{|\}|\(|\)|\-|\+|\=)/g, '\\$1')
      let regexp
      if (str === '*') {
        regexp = new RegExp('/' + str + '/', 'i')
      } else {
        regexp = new RegExp(str, 'i')
      }
      return regexp.test(params.host || '')
    })
    return this.json({
      status: 200,
      data: {
        scripts: _script || [],
      },
      message: '成功'
    })
  }
}
